#include <ServoC.h>

#include "WProgram.h"
void setup();
void loop();
void sampling();
void printTime();
void printdata();
int value = 0;                            // variable to keep the actual value 
int potPin=2;
int capacity = 800;
int data[800];
int current =-1;
int last = -1;
int size =0;
int numz =0;
int val;
int ledPin = 13;                 // LED connected to digital pin 13
unsigned long startTime;
ServoC myservo(13,90, 300, 1500);
boolean islastsamplesignal = false;

void setup() 
{ 
  Serial.begin(9600);
  // nothing for setup a
  pinMode(ledPin, OUTPUT); 
  
} 
 
void loop() 
{
    Serial.println(myservo.readpulse()); 
    sampling();      // take capacity=800 samples
    if( islastsamplesignal == true)
    {
    if(myservo.readangle()!=180)
      myservo.write(180);
    else
      myservo.write(90);
    }
    myservo.refresh();
      
}
 
//end of loop()


void sampling()
{
  
     val = analogRead(potPin);
   //detect new signal
   if( val !=0)
   { 
     Serial.println(myservo.readpulse());
     data[size++]=val;
     startTime = millis();
     digitalWrite(ledPin, HIGH);   // sets the LED on
    while(true)
   {
    if(size >= capacity)
      {
        break;
      }
      current = analogRead(potPin);
      if( current == 0 && last != 0)
      {
        numz=1;
      }
      else if( current ==0 && last ==0)
      {
        numz++; 
        if(numz > 200)
        break;
      }
      
      last = current;
      data[size++] = current;
      delayMicroseconds(1000); //sampling rate
   }
   digitalWrite(ledPin, LOW);   // sets the LED off
// printdata();
   size=0;
   numz=0;
   islastsamplesignal=true;
 //  delay(3000); //stop before we take another signal
   }
   
   else
   {
     islastsamplesignal = false;
   }
}

void printTime()
{
   Serial.print("Time:");
   Serial.println( millis() - startTime);
  
   Serial.print("millis:");
   Serial.println( millis() );

   Serial.print("startTime:");
   Serial.println( startTime );

   Serial.print("zeros:");
   Serial.println(numz); 
}

void printdata()
{
   Serial.print("S");
   for(int i=0; i< size; i++)
   {
    Serial.println(data[i]); 
   }
   Serial.print("E");
} 





int main(void)
{
	init();

	setup();
    
	for (;;)
		loop();
        
	return 0;
}

